/**
 * 首页
 */
var index = {
    /** 初始化首页功能*/
    init:function () {
        // 初始化输入框事件
        this.inputChange();
        this.initLogin();
//        this.initHelpCenter();
        this.initKeyBordEvent();
        this.showMenu();
        this.initBanner();
        this.forgetPassword();
        this.showPop();
        this.orderBtn();
        this.initWordLink();
        this.seeDetail();
        this.proNameClick();
        // 初始化弹窗广告
        this.initBannerPopup();
    },

    /** 初始化文字链事件 */
    initWordLink:function () {
        $('#rolling p').each(function () {

            var r_type = $(this).attr('rtype');
            /** 1 链接分类linkedClassid
			 *  2 链接静态URL linkedUrl
			 */
            if (r_type == 2) {
                var linkurl = $(this).attr('linkurl');
                $(this).find('a').attr({target:'_blank', href:linkurl});
            } else if (r_type == 1) {
                var _href = $('a[pid=' + $(this).attr('linkcid') + ']').attr('href');
                $(this).find('a').attr({href:_href});
            }
        });
    },

    /** 首页列表栏绑定链接静态页面的事件*/
    showMenu:function () {
        $("#nav li ul li a").each(function () {
            var t = $(this).attr('t');
            var menuPath = httpHtmlPath+"/" + $(this).attr('menuPath');
            //limingjiang 2013-05-10 start
            //$(this).attr('href', "/kfcios/html/" + t + ".html");
            $(this).attr('href', menuPath + ".html");
            //limingjiang 2013-05-10 end
        });

    },

    /** 绑定图片点击事件*/
    showPop:function () {
        $('.showPicPop').click(function () {
            var pid = $(this).attr('productid');
            var mFlag = $(this).attr('mFlag');
            var linkType = $(this).attr('linkType');
            var vClassId = $(this).attr('classId');
            var virtualLink = $(this).attr('virtualLink');
            if (mFlag == "V") {
                index.vClick(linkType, vClassId, virtualLink);
                return;
            }
            index.popupConShow(pid, $(this));
        });
    },

    /** 绑定[查看详情]按钮*/
    seeDetail:function () {
        $('.see_details_btn').click(function () {
            var $a_showP = $(this).closest('.pro_info').prev();
            var linkType = $a_showP.attr('linkType');
            var vClassId = $a_showP.attr('classId');
            var virtualLink = $a_showP.attr('virtualLink');
            index.vClick(linkType, vClassId,virtualLink);
        });
    },
    
    /** 绑定虚拟产品描述点击事件*/
    proNameClick:function(){
    	var $proName = $('.pro_name');
    	$proName.click(function () {
    		 var $a_showP = $(this).closest('.pro_info').prev();
             var mFlag = $a_showP.attr('mFlag');
             if (mFlag == 'V'){
            	 var linkType = $a_showP.attr('linkType');
                 var vClassId = $a_showP.attr('classId');
                 var virtualLink = $a_showP.attr('virtualLink');
            	 index.vClick(linkType, vClassId,virtualLink);
             }
    	});
    },

    /** 虚拟产品点击事件*/
    vClick:function (linkType, vClassId,virtualLink) {
        /** linkType 1:classId,2:url*/
        if (linkType == 1) {
        	window.location.href = $('a[pid=' + vClassId + ']').attr('href');
            $('a[pid=' + vClassId + ']').click();
        } else if (linkType == 2) {
            window.open(virtualLink);
        }
    },

    /** 【开始订餐】按钮事件*/
    orderBtn:function () {
        $('.order_btn_start').click(function () {
            location.href = requestContextPath + '/login.action';
        });
    },

    /** 初始化广告域 */
    initBanner:function () {
        $(".index_banner,.sbanner").find("img").each(function (index, element) {
            var linkType = $(this).attr('linkType');
            if (linkType == 1) {
                var _href = $('a[pid=' + $(this).attr('classId') + ']').attr('href');
                $(this).parent('a').attr({href:_href});
            } else if (linkType == 2) {
                var linkedurl = $(this).attr('linkedurl');
                $(this).parent('a').attr({target:'_blank', href:linkedurl});
            }
        });
    },

    /** 获取登陆框对象*/
    getFormInfo:function () {
        return {
            form:document.forms.myForm,
            showPassWord:$('#showPwd'),
            showEmail:$('#showEmail')
        };

    },

    /** 初始化帮助中心*//*
    initHelpCenter:function () {
        // 绑定【新手入门】的点击事件
        $('.help_h1').live('click', function () {
            window.location.href = requestContextPath + '/jsp/help/help_new.html';
        });

    },*/

    /** 初始化登陆框*/
    initLogin:function () {
        // 获取用户记录的信息
        var mobile = $.cookie(yumCfg.rememberUser);
        if (mobile) {
            $('#mobi').val(mobile);
            $('#input_reme').prop('checked', true);
        }

        // 绑定提交按钮事件
        $('#loginSubmit').click(this.loginAction());

    },

    /** 手机，邮箱和密码输入框事件
     * 当输入框中的值发生变化的时候，隐藏输入框，
     * 并清空该框中的值
     */
    inputChange:function () {
        // 获取表单中的对象
        var getFormIonf = this.getFormInfo();
        var form = getFormIonf.form;

        // 获取密码输入框和邮箱输入框的JQUERY对象
        var showPassWord = getFormIonf.showPassWord;
        var showEmail = getFormIonf.showEmail;

        // 绑定隐藏和清空输入框的事件-- 邮箱输入框
        $(form.mobi).live('click keyup', function () {
            // 隐藏输入框
            showPassWord.hide();
            showEmail.hide();

            // 清空输入框中的值
            form.password.value = '';
            form.email.value = '';
        });

        // 绑定隐藏和清空输入框的事件-- 密码输入框
        $(form.email).live('click keyup', function () {
            // 隐藏邮箱输入框
            showPassWord.hide();
            // 清空邮箱输入框中的值
            form.password.value = '';
        });
    },

    /** 提交按钮绑定键盘回车事件*/
    initKeyBordEvent:function () {
        var _me = this;
        var getFormIonf = _me.getFormInfo();
        var keyupEnent = function (event) {

            // 键盘的回车事件编号为"13"
            if (event.which == 13) {

                // 判断导航栏标示(1:用户点击【订单查询】)
                if ($('#checkFlag').val() == 1) {
                    _me.loginAction();
                } else {

                    // 判断是否在营业时间内
                    //                    base.inOper(function() {
                    _me.loginAction()();
                    //                    });
                }
            }
        };
        $(getFormIonf.form.mobi).keyup(keyupEnent);
        $(getFormIonf.form.email).keyup(keyupEnent);
        $(getFormIonf.form.password).keyup(keyupEnent);
    },

    /** 登陆表单提交Action*/
    loginAction:function () {
        // 获取表单元素数据
        var getFormInfo = this.getFormInfo();

        return function () {
            var form = getFormInfo.form;
            //
            var showPassWord = getFormInfo.showPassWord;
            var showEmail = getFormInfo.showEmail;

            var mobile = form.mobi.value;
            var email = form.email.value;
            var passWord = form.password.value;

            var mobileValue = $.trim(mobile);
            var emailValue = $.trim(email);
            var passwordValue = passWord;

            var args = {
                showPassWord:showPassWord,
                showEmail:showEmail,
                mobile:mobile,
                email:email,
                passWord:passWord,
                emailEl:form.email
            };

            // 对以上参数进行有效验证
            if (index.validForm(args)) {
                $.ajax({
                    url:requestContextPath + '/loginValidate.action',
                    data:{
                        mobi:mobileValue,
                        email:emailValue,
                        pass:passwordValue
                    },
                    dataType:'json',
                    type:'post',
                    success:function (data) {
                        switch (data.code) {
                            // 正常，登陆到用户信息页面
                            case serviceCode.SUC_CODE:
                                if ($("#input_reme").prop("checked")) {
                                    $.cookie(yumCfg.rememberUser, mobileValue, {expires:yumCfg.keep});
                                } else {
                                    $.cookie(yumCfg.rememberUser, null);
                                }
                                if ($("#checkFlag").val() == 1) {
                                    base.setAction('check.action');
                                } else {
                                    base.setAction('customer.action');
                                }
                                setTimeout(function(){form.submit();}, 500);
                                break;
                            // 用户不存在
                            case serviceCode.CUSTOMER_NOT_FOUND:
                                if ($("#input_reme").prop("checked")) {
                                    $.cookie(yumCfg.rememberUser, mobileValue, {expires:yumCfg.keep});
                                } else {
                                    $.cookie(yumCfg.rememberUser, null);
                                }
                                if ($("#checkFlag").val() == 1) {
                                    base.yumAlert(property.notExsitRecord);
                                } else {
                                	if($(form.mobi).is(':visible') && $(form.email).is(':visible')){
                                		base.yumConfirm(property.noMatchInfo, function(){
                                			base.setAction('agreement.action');
                                		});
                                	}else{
                                		base.setAction('agreement.action');
                                	}
                                }
                                break;
                            // 用户为转网用户
                            case serviceCode.NET_USER:
                            	base.setAction("toNetUserLogin.action");
                            	break;
                            // 客户为密码用户，需提供密码进行登录
                            case serviceCode.NEED_PASSWORD:
                                showPassWord.show();
                                break;
                            // 客户输入错误的密码
                            case serviceCode.INCORRECT_PASSWORD:
                                base.yumAlertBack(property.passNotCorrect, function () {
                                    password.value = '';
                                });
                                break;
                            // 对应多个mail
                            case serviceCode.MULTI_CUSTOMER_FOUND:
                                showEmail.show();
                                break;
                            default:
                                base.yumAlert(property.serviceUnknown);
                        }
                    },
                    error:function () {
                        alert(property.BadRequest);
                    }
                });
            }
        };

    },

    /** 验证表单的有效性*/
    validForm:function () {

        // 获取需要验证的参数
        var args = arguments[0];
        var mobileValue = $.trim(args.mobile);
        var emailValue = $.trim(args.email);
        var passwordValue = args.passWord;
        var showEmail = args.showEmail;
        var showPassWord = args.showPassWord;

        if (mobileValue == '') {
            base.yumAlert(property.EorPNotNull);
            return false;
        }
        if (common.isMobile(mobileValue) || common.isEmail(mobileValue)) {
            if (showEmail.is(':visible') && emailValue == '') {
                base.yumAlert(property.emailNotNull);
                return false;
            }
            if (emailValue != '' && !common.isEmail(emailValue)) {
                base.yumAlertBack(property.emailNotcorrect, function () {
                    args.emailEl.value = '';
                    args.emailEl.focus();
                });

                return false;
            }
            if (showPassWord.is(':visible') && passwordValue == '') {
                base.yumAlert(property.pwdNotNull);
                return false;
            }
        	if(showPassWord.is(':visible') && !/^[a-zA-Z0-9]{6,16}$/.test(passwordValue)){
				base.yumAlert(property.EorPasswordFormat);
				return false;
			}
        	if(common.isStr2(passwordValue,3) || common.isStr2(emailValue,1)||common.isStr2(mobileValue,1)){
        		base.yumAlert(property.invaildStringError);
				return false;
        	}

            return true;
        } else {
            base.yumAlert(property.EorPNotcorrect);
            return false;
        }
    },

    //-- 忘记密码
    forgetPassword:function () {
        var forgetBtn = $('.forgetPwd');
        var formInfo = this.getFormInfo();
        var showEmail = formInfo.showEmail;
        var form = formInfo.form;

        var mobile = form.mobi;
        var email = form.email;

        forgetBtn.click(function () {
            var mobileValue = $.trim(mobile.value);
            var emailValue = $.trim(email.value);
            var mobiOrMail = showEmail.is(':visible') ? emailValue : mobileValue;
            $.ajax({
                url:requestContextPath + '/findPassword.action',
                data:{mobiOrMail:mobiOrMail},
                dataType:'json',
                type:'post',
                success:function (o) {
                    if (o.code == serviceCode.SUC_CODE) {
                        base.yumAlert(property.resetMail.format([o.message]));
                    } else if (o.code == serviceCode.MAIL_SEND_FAIL) {
                        base.yumAlert(property.emailSendFail);
                    } else {
                        base.yumAlert(property.serviceUnknown);
                    }
                }
            });
        });
    },

    /***
     * 点击商品的图片,与订购按钮弹出框
     * @param pid 商品Id
     * @param args 商品属性对象
     * name:zhu_jiaLei
     * date:2013-04-16
     */
    popupConShow:function (pid, args) {
        var promHtml = "";

        if (pid) {
            promHtml = this.getAjaxHtml(httpHtmlPath + '/' + pid + '.html');//获取优惠列表html
            this.PromotionHtml(args, promHtml);//组建弹出框内容
            this.PopUp_Show_Html($('#menuPopupConShow'));//调用弹出框进行弹出
        } else {
            location.href = requestContextPath + '/login.action';//链接转向至登陆界面
        }
    },

    /***
     * 创建优惠界面
     * @param type 商品显示状态页面
     * @param promHtml 优惠静态页面
     * @returns 返回静态页面对象
     * name:zhu_jiaLei
     * date:2013-04-16
     */
    PromotionHtml:function (args, promHtml) {

        var menuPopUpShow = $('#menuPopupConShow').find('.popup_product_detail>div');

        /** 获取对应的产品参数*/
        var pro_img = args.find('[name=menuImg]').attr('src');
        var pro_price = args.attr('price');
        var pro_menuCnTemp = args.attr('menu');
        var pro_menuCn = $.localStr({cn:pro_menuCnTemp,en:pro_menuCnTemp}, 1);      
        var pro_desc = args.attr('desc');
        var pro_st = args.attr('saleTime');
        var pro_svd = args.attr('sVD');
        var pro_Area = args.attr('area');
        var $nco = args.closest('li').find('.ncoFlag').clone();
        //供应日期国际化 start
        var validFrom=args.attr('validFrom');
        var validTo=args.attr('validTo');
        //转换日期格式
        var saleValidFrom=new Date(validFrom);
        var saleVaildTo=new Date(validTo);
        var saleValidFrom2=saleValidFrom.getFullYear()+'/'+(saleValidFrom.getMonth()+1)+'/'+saleValidFrom.getDate();
        //getMonth()从0到11
        var saleVaildTo2=saleVaildTo.getFullYear()+'/'+(saleVaildTo.getMonth()+1)+'/'+saleVaildTo.getDate();
        var saleValidDate=null;
        if(saleVaildTo2=='2099/12/31'){
        	//全年
        	saleValidDate=property.ThroughoutTheYear;
        }else{
        	//2012/01/01--2013/01/01
        	saleValidDate=saleValidFrom2+'--'+saleVaildTo2;
        }
        
        var $img = menuPopUpShow.find(".popup_product_detail_img>img");
        $img.attr({"src":pro_img}).width('130px').height('111px').css('margin-left','8px');
        $img.siblings('span').remove();//清除角标
        if ($nco) {
        	$nco.find('img').width('130px').height('111px');
            $img.after($nco);
        }
        menuPopUpShow.find(".title_span_1").empty().append(pro_menuCn);
        menuPopUpShow.find("#desc").empty().append(pro_desc);
        menuPopUpShow.find('#saleTime').empty().text(property.avaliableTime+ pro_st);
        //menuPopUpShow.find('#saleValidDate').empty().text(property.avaliableDate+ pro_svd);
        menuPopUpShow.find('#saleValidDate').empty().text(property.avaliableDate+ saleValidDate);
        //供应日期国际化 end
        menuPopUpShow.find('#promotionArea').empty().text(property.avaliableZone + pro_Area);
        //点击弹出页面的价格
    	if($.isEnglish()){
    		menuPopUpShow.find(".price_span_1").empty().append($('<span/>').html(pageMessage.yun)).append(pro_price);//args.proPra
    	}else{
    		menuPopUpShow.find(".price_span_1").empty().append(pro_price).append($('<span/>').html(pageMessage.Yuan_Per));//args.proPra
    	}
        menuPopUpShow.find(".input_span").hide();

        var menuPreferShow = $('#menuPopupConShow').find('.popup_main_title_product');
        menuPreferShow.empty();
        menuPreferShow.append(promHtml);
        //关闭弹出框
        $("#menuPopupConShow").find('.close_icon>a').live('click', function () {
            $("#menuPopupConShow").dialog('close');
        });
        //点击转向页面进入登陆界面
        $('#menuPopupConShow').find('#loginBtn').live('click', function () {
            $("#menuPopupConShow").dialog('close');
            location.href = requestContextPath + '/login.action';
        });
    },

    /**
     * 创建弹出框
     * @param type dialogClass 样式类型()
     * @param show_html 弹出页面对象
     * name:zhu_jiaLei
     * date:2013-04-16
     */
    PopUp_Show_Html:function (show_html) {
        var middle_bg = 'big_bg';//点击图片弹出优惠框
        show_html.dialog({
            resizable:false,
            height:"auto",
            width:555,
            draggable:false,
            fixed:false,
            dialogClass:middle_bg,
            position:{my:"center", at:"center", of:window, collision:"fit"},
            modal:true
        });
    },

    /***ajax 请求静态页面
     * @param urlAction 请求url
     * name:zhu_leiJia
     * date:2013-04-16
     */
    getAjaxHtml:function (urlAction) {
        var d = null;
        $.ajax({
            url:urlAction,
            type:'GET',
            async:false,
            success:function (data) {
                d = data;
            }
        });
        
        /** 由于服务器对于请求不到的URL会自动转发到
         * index.hmtl页面，导致没有优惠产品的弹出框
         * 在请求不到优惠弹窗的url也会自动转发到index.hmtl
         * 并填充弹窗中，判断优惠弹框页面标示，目前优惠没有
         * 弹窗标示，对于请求到的页面中存在标示，清空返回页
         * 面结果。 wanglei 20130803 start */
        var pageFlag = $(d).find('#page_flag');
        if (pageFlag && pageFlag.val()){
            
            d = null;
        }
        /** wanglei 20130803 end */
        return d;
    },
    
    /** 初始化跳屏广告*/
    initBannerPopup: function(){
		if($(".popBannerList").length>0) {
			var isBannerPopupIndex = $.cookie("isBannerPopupIndex"); //是否首页弹出
			var isBannerPopupLogin = $.cookie("isBannerPopupLogin"); //是否登录后弹出
			
			$('.popBannerList').each(function(){
				var _me = $(this);
				var startTime = _me.find('.bannerPopup a img').attr('startTime');
				var endTime = _me.find('.bannerPopup a img').attr('endTime');
				var time = startTime+'-'+endTime;
				
				if (index.vaildTime(time)){
					index.showPopBanner(isBannerPopupIndex,isBannerPopupLogin,_me);
					return false;
				}
				
			});
			
		};
	},
	
	showPopBanner:function(isBoIndex, isBpLogin, $this){
		var isPop = $this.find("#isPop"); //广告类型 3为首页 4为登录后
		var widthAll = $(document).width();
		
		
		
		var $bannerPop = $this.find('.bannerPopup');
		var $bannerPopupBg = $this.find('.bannerPopupBg');
		var $bannerPopupSmall =$this.find('.bannerPopupSmall');
		
		if($.browser.chrome) { // 解决Chrome下不兼容问题
			$bannerPop.show({complete: function() {
				$bannerPop.css("left",(widthAll-$bannerPop.width())/2);
			}});
		} else {
			var widthImage = $bannerPop.show().width();
			$bannerPop.css("left",(widthAll-widthImage)/2);
		}
		if($.browser.msie && $.browser.version==6){
			$bannerPopupBg.height($(document).height()).width($(document).width());
			$(window).scroll(function(){
				$bannerPopupSmall.css({"bottom":"","top":$(window).height()+$(window).scrollTop()-5-$bannerPopupSmall.height()});
			});
		}
		if((isBoIndex == null && isPop.val() =='1')){
			$bannerPopupBg.show();
			$bannerPop.show();
			
			$.cookie("isBannerPopupIndex","false");

			setTimeout(function(){
				$bannerPopupBg.hide();
				$bannerPop.hide();
				$bannerPopupSmall.show();
			},6000);
		}else{
			$bannerPopupBg.hide();
			$bannerPop.hide();
			$bannerPopupSmall.show();
		}
		
		// 初始化图片点击事件
		var $bannerImg = $bannerPop.find('a img');
		var linkType = $bannerImg.attr('linkType');
         
		if (linkType == 1) {
			var _href = $('a[pid=' + $bannerImg.attr('classId') + ']').attr('href');
			$bannerImg.parent('a').attr({href:_href});
		} else if (linkType == 2) {
			var linkedurl = $bannerImg.attr('linkedurl');
			$bannerImg.parent('a').attr({target:'_blank', href:linkedurl});
         
		}else{
			$bannerImg.parent('a').die().live('click', function(){
				$bannerPopupBg.hide();
				$bannerPop.hide();
				$bannerPopupSmall.show();
			});
		}
		
		//缩略图点击事件
		$bannerPopupSmall.live("click",function(){
			if($.browser.msie && $.browser.version==6){
				$bannerPopupBg.height($(document).height()).width($(document).width());
			}
			$bannerPopupBg.show();
			$bannerPop.show().css("left",($(document).width()-$bannerPop.width())/2);
			$bannerPopupSmall.hide();
		});
		//关闭按钮点击事件
		$this.find(".bannerPopupBg,.closeBannerPopup").live("click",function(){
			$bannerPopupBg.hide();
			$bannerPop.hide();
			$bannerPopupSmall.show();
		});
	},
	
	/**
	 * 验证当前时间是否为广告显示时间
	 * 
	 * @param time
	 *            分类可售时间
	 * @param flag
	 *            分类标示
	 * @return {Boolean}
	 */
	vaildTime : function(time) {
		var date = new Date();
		var hours = date.getHours() * 100;
		var minutes = date.getMinutes();

		var total = parseInt(hours) + parseInt(minutes);

		var bArry = time.split('-');

		var startTime = 0;
		var endTime = 0;
		for ( var i = 0; i < bArry.length; i++) {
			var b = bArry[i].split(':');
			for ( var j = 0; j < b.length; j++) {
				if (i == 0) {
					if (j == 0) {
						startTime += parseInt(b[j]) * 100;
					} else {
						startTime += parseInt(b[j]);
					}
				} else {
					if (j == 0) {
						endTime += parseInt(b[j]) * 100;
					} else {
						endTime += parseInt(b[j]);
					}
				}
			}
		}
		
		if (startTime>endTime){
			if (startTime <= total && total <= 2359) {
				return true;
			} else if (0 <= total && total <= endTime) {
				return true;
			}
		}else{
			if (startTime <= total && total <= endTime) {
				return true;
			}
		}
		return false;
	}
};